import 'dart:async';

import 'package:connectivity/connectivity.dart';
import 'package:flutter/rendering.dart';
import 'package:fluttertoast/fluttertoast.dart';


enum NetWorkStatus {
  Unknown,
  Wifi,
  Mobile,
}

NetWorkStatus globalStatus = NetWorkStatus.Unknown;

class CYNetwork {
  NetWorkStatus status = globalStatus;
  StreamSubscription<ConnectivityResult> _streamSubscription;

  CYNetwork() {
    getStatus();
  }

  Timer durationTimer;
  handleChangeStatus(ConnectivityResult result, [VoidCallback onChange]) {
    if(durationTimer != null && durationTimer.isActive) {
      durationTimer.cancel();
    }
    durationTimer = Timer(Duration(milliseconds: 500), () {
      _switchStatus(result);
      if(onChange != null) {
        onChange();
      }
    });
  }

  check([VoidCallback onChange]) {
    _streamSubscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result){
      handleChangeStatus(result, onChange);
    });
  }

  _switchStatus(ConnectivityResult result) {
    switch (result) {
        case ConnectivityResult.mobile:
          status = NetWorkStatus.Mobile;
          break;
        case ConnectivityResult.none:
          status = NetWorkStatus.Unknown;
          break;
        case ConnectivityResult.wifi:
          status = NetWorkStatus.Wifi;
          break;
        default:
          break;
      }

      if(result== ConnectivityResult.none && globalStatus != status) {
        Fluttertoast.showToast(
          msg: "网络链接错误，请重新链接网络", 
          gravity: ToastGravity.CENTER, 
          toastLength: Toast.LENGTH_LONG,
          timeInSecForIosWeb: 1,
          fontSize: 16.0
        );
      }

      if(globalStatus != status) {
        globalStatus = status; 
      }
  }

  void dispose() { 
    if(durationTimer != null && durationTimer.isActive) {
      durationTimer.cancel();
      durationTimer = null;
    }
    if(_streamSubscription!=null) {
      _streamSubscription.cancel();
      _streamSubscription = null;
    }
  }

  Future<NetWorkStatus> getStatus() async {
    var result = await Connectivity().checkConnectivity();
    _switchStatus(result);
    return status;
  }
}
